package main

import (
	"context"
	"encoding/json"
	"fmt"
	"github.com/olivere/elastic/v7"
	"log"
	"os"
)

type User struct {
	Firstname string `json:"firstname"`
	Age       int    `json:"age"`
}

const mapping = `
{
	"mappings":{
		"properties":{
			"name":{
				"type":"text",
				"analyzer":"ik_max_word"
			},
			"id":{
				"type":"integer"
			}
		}
	}
}`

func Match(client *elastic.Client) {
	query := elastic.NewMatchQuery("address", "street")
	result, err := client.Search().Index("user").Query(query).Do(context.Background())
	if err != nil {
		panic(err)
	}
	fmt.Println(result.Hits.TotalHits.Value)

	var users []User
	for _, value := range result.Hits.Hits {
		u := User{}
		if err := json.Unmarshal(value.Source, &u); err != nil {
			panic(err)
		}
		users = append(users, u)

	}
	fmt.Println(users)
}

func Insert(client *elastic.Client) {

	user := User{
		Firstname: "xiaoming",
		Age:       20,
	}
	do, err := client.Index().Index("myuser").BodyJson(user).Do(context.Background())
	if err != nil {
		panic(err)
	}
	fmt.Printf("index myuser id:%s index:%s type:%s", do.Id, do.Index, do.Type)
}

func AddIndex(client *elastic.Client) {
	createIndex, err := client.CreateIndex("goods").BodyString(mapping).Do(context.Background())
	if err != nil {
		panic(err)
	}
	if !createIndex.Acknowledged {
		fmt.Println("err")
	}
}

func main() {

	host := "http://127.0.0.1:9200"
	logger := log.New(os.Stdout, "mxshop", log.LstdFlags)
	client, err := elastic.NewClient(elastic.SetURL(host), elastic.SetSniff(false), elastic.SetTraceLog(logger))
	if err != nil {
		panic(err)
	}
	//Insert(client)
	AddIndex(client)
}
